
import 'package:valovault_reminder/common/bean/val_user_base_info_model.dart';
import 'package:valovault_reminder/common/config/val_assets_name.dart';
import 'package:valovault_reminder/common/config/val_client_url_path.dart';
import 'package:valovault_reminder/common/ui/val_ui_kit_dialog_impl.dart';
import 'package:valovault_reminder/common/util/val_app_state_tool.dart';
import 'package:valovault_reminder/http/val_dio_fetch_kit.dart';
import 'package:valovault_reminder/pages/base/val_base_ui_page.dart';
import 'package:valovault_reminder/pages/home/components/val_switch_button_menu.dart';
import 'package:valovault_reminder/pages/home/val_home_maintenance_detail_page.dart';
import 'package:valovault_reminder/util/val_screen_size_kit.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:valovault_reminder/util/val_eventbus_manager.dart';

import '../../common/ui/val_none_data_view.dart';
import '../mine/views/val_user_publish_card_content_cell.dart';
import 'components/val_home_car_body_cell.dart';
import 'components/val_home_delete_alert_view.dart';
import 'models/val_post_record_model.dart';

class ValApplicationHomePage extends StatefulWidget {
  const ValApplicationHomePage({super.key});

  @override
  State<ValApplicationHomePage> createState() => _ValApplicationHomePageState();
}

class _ValApplicationHomePageState extends ValBaseUIPageState<ValApplicationHomePage> {
  bool selectedMenu = true;
  List<ValPostRecordModel> _listData = [];
  List<ValPostRecordModel> _accidentData = [];

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    isAppBar = false;
    extendBodyBehindAppBar = true;
    bgColor = const Color(0xFF143B42);
    requestAccountDetailInfo();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {

    });

    ValEventbusManager.getInstance().eventBus.on().listen((event) {
      if (event.toString() != "postContent") {
        return;
      }

      loadRecordData();
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  Future<void> loadRecordData() async {
    String category = selectedMenu ? '1' : '2';
    List<ValPostRecordModel> list = await ValPostRecordModel().readCategoryDb(category);
    if (selectedMenu) {
      _listData = list;
    }
    else {
      _accidentData = list;
    }

    setState(() {

    });
  }

  ///进入详情界面
  void jumpToRecordDetailPage(int position, ValPostRecordModel listModel) {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) {
        return ValHomeMaintenanceDetailPage(listModel: listModel,);
      }),
    );
  }

  ///获取账号信息
  void requestAccountDetailInfo() {
    ValDioFetchKit.getInstance().getJsonWithUrl(ValClientUrlPath.userInfo, {'userId' : ValAppStateTool().userId},
        (data, errorCode, message){
      if (errorCode == 0) {
        ValUserBaseInfoModel user = ValUserBaseInfoModel.fromJson(data);
        ValAppStateTool().accountInfo = user;
        loadRecordData();
        print('账号信息:${ValAppStateTool().accountInfo?.nickname}');
      }
    }, (err) {

    });
  }

  Widget carCollection() {
    return Positioned(
      top: 377, left: 0, right: 0, bottom: ValScreenSizeKit.getBottomBarH(context),
      child: (!selectedMenu && _accidentData.isEmpty) ? const ValNoneDataView() : Container(
        decoration: const BoxDecoration(
          color: Color(0xFF1D3231),
          borderRadius: BorderRadius.only(topLeft: Radius.circular(40))
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Container(
              padding: const EdgeInsets.only(top: 12, right: 20, bottom: 8),
              child: const Text('Your Accident Record',
                textAlign: TextAlign.right, maxLines: 1,
                style: TextStyle(color: Colors.white, fontSize: 20),),
            ),
            Expanded(
              child: GridView.builder(
                padding: const EdgeInsets.only(top: 12, left: 20, bottom: 12, right: 20),
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2, //列数
                  childAspectRatio: 158.0/182.0, //显示区域宽高相等
                  crossAxisSpacing: 10,
                  mainAxisSpacing: 10,
                ),
                itemCount: _accidentData.length,
                itemBuilder: (context, index) {
                  ValPostRecordModel postModel = _accidentData[index];
                  return ValUserPublishCardContentCell(
                    contentText: postModel.content,
                    userName: postModel.publishDate,
                    imageName: postModel.coverImage,
                    userHeader: postModel.accountImage,
                    showDelete: true,
                    onTapCard: () {
                      jumpToRecordDetailPage(index, postModel);
                    },
                    onTapDelete: () {
                      _showDeleteView(postModel);
                    },
                  );//Container(color: Colors.cyan, child: Icon(Icons.cake));
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _showDeleteView(ValPostRecordModel postModel) {
    ValUIKitDialogImpl.showCenter(ValHomeDeleteAlertView(() {
      postModel.deleteDb(postModel);
      loadRecordData();
    }));
  }

  @override
  Widget buildBody(BuildContext context) {
    // if (selectedMenu && _listData.isEmpty || !selectedMenu && _accidentData.isEmpty) {
    //   return const ValNoneDataView();
    // }
    return AnnotatedRegion(
      value: SystemUiOverlayStyle.light,
      child: Stack(
        children: [
          Image.asset('${ValAssetsName.ASSETS_HOME}${selectedMenu ? 'val_home_ground.png' : 'val_home_accident_ground.png'}',
            height: double.infinity,
            width: double.infinity,
            fit: BoxFit.fill,),
          if (selectedMenu)
          Positioned(
              top: 80, left: 0, right: 0, height: 342,
              child: Container(
                decoration: const BoxDecoration(
                  color: Colors.transparent,
                  image: DecorationImage(
                      image: AssetImage('${ValAssetsName.ASSETS_HOME}val_home_top_car.png'),
                      fit: BoxFit.fitWidth),
                ),
              )
          ),
          Positioned(
              top: 64, left: 46, right: 46, height: 46,
              child: ValSwitchButtonMenu(onString: "Maintenance", offString: "Accident", pressed: selectedMenu, onTap: (index){
                setState(() {
                  selectedMenu = index == 0 ? true : false;
                });
                requestAccountDetailInfo();
              }),
          ),

          !selectedMenu ? carCollection() : Positioned(
            top: 377,
            left: 0,
            right: 0,
            bottom: ValScreenSizeKit.getBottomBarH(context),
            child: selectedMenu && _listData.isEmpty ? const ValNoneDataView() : ListView.builder(
              padding: const EdgeInsets.only(bottom: 10),
              itemCount: _listData.length,
              itemBuilder: (BuildContext content, int position) {
                ValPostRecordModel data = _listData[position];
                return GestureDetector(
                  onTap: () {
                    jumpToRecordDetailPage(position, data);
                  },
                  child: ValHomeCarBodyCell(
                    title: data.title,
                    imageName: data.image,
                    content: data.publishDate,
                    onTap: (){
                      jumpToRecordDetailPage(position, data);
                    },
                    onTapDelete: (){
                      _showDeleteView(data);
                    },
                  ),
                );
              },
            ),
          )
        ],
      ),
    );
  }
}
